//-----------------------------------------------------------------------
// <copyright file="Execute.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// </copyright>
// <author>Giles Knap</author>
// <email>gilesk</email>
// <date>2006-05-02</date>
// <summary>Sets the database version.</summary>
//-----------------------------------------------------------------------


namespace Microsoft.Sdc.Tasks.Sql
{
    using System;
    using System.Xml;
    using System.Globalization;
    using System.IO;
    using System.Data;
    using System.Data.SqlClient;
    using SdcSql = Microsoft.Sdc.Tasks.Configuration.SqlServer;
    using Microsoft.Build.Framework;

    /// <summary>
    /// Sets an extended property 'DatabaseVersionNumber' on the database specified in the connection string. This can be used in
    /// conjunction with 'GetDatabaseVersion' to control db initialization/upgrade scripts in installers etc.
    /// </summary>
    /// <remarks>
    /// <code><![CDATA[<Sql.Execute DatabaseVersion="versionNumber" ServerName="serverName" DatabaseName="database" ConnectionString="oleDBConnectionString" CommandTimeout="timeout" />]]></code>
    /// <para>where:</para>
    /// <para><i>serverName</i></para>
    /// <para>The server hosting the database (ignored if a connection string is supplied)</para>
    /// <para><i>databaseName</i></para>
    /// <para>The database (ignored if a connection string is supplied)</para>
    /// <para>If you do not specify a server and database name you must specify a 
    /// <see cref="ConnectionString">connection string</see>.</para>
    /// <para><i>connectionString</i></para>
    /// <para>An OLE/DB connection string detailing the connection parameters required.</para>
    /// <para>If you do not specify a connection string you must specify a
    /// <see cref="ServerName">serverName</see> and <see cref="DatabaseName">databaseName</see></para>
    /// <para><i>timeout</i></para>
    /// <para>Maximum time allowed to perform the task (seconds)</para>
    /// </remarks>
    /// <example>
    /// <code><![CDATA[
    /// <Project>
    ///     <Target Name="Test" >
    ///         <Sql.SetDatabaseVersion
    ///             DatabaseVersion="2.1"
    ///             ServerName="(local)"
    ///             DatabaseName="testDB"
    ///             CommandTimeout="60" />
    ///     </Target>
    /// </Project>
    /// ]]></code>    
    /// </example>
    [Obsolete("Please review the functionality provided by the new Sql.ExtendedProperty class")]
    public class SetDatabaseVersion : TaskBase
    {
        private string connectionString = String.Empty;
        private string databaseVersion = String.Empty;
        private string serverName = String.Empty;
        private string databaseName = String.Empty;
        private int commandTimeout = 30;

        /// <summary>
        /// Initializes a new instance of the SetDatabaseVersion class.
        /// </summary>
        public SetDatabaseVersion()
        {
        }

        /// <summary>
        /// Performs the action of this task which is to execute T-SQL scripts.
        /// </summary>
        protected override void InternalExecute()
        {
            string commandText = null;

            #region Execute code

			System.Reflection.Assembly assem = this.GetType().Assembly;
            using (Stream stream = assem.GetManifestResourceStream("Microsoft.Sdc.Tasks.Sql.SetDatabaseVersion.sql"))   
			{
				using( StreamReader reader = new StreamReader(stream) )         
				{
                    commandText = reader.ReadToEnd();         
				}
			}

            if (String.IsNullOrEmpty(connectionString))
            {
                connectionString = string.Format(
                    "Data Source={0};Integrated Security=SSPI;Initial Catalog={1}",
                    serverName,
                    databaseName);
            }
            
            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                SqlCommand command = new SqlCommand(commandText, sqlConnection);
                command.CommandTimeout = commandTimeout;

                SqlParameter dbVersion = new SqlParameter("DbVersion",databaseVersion);

                command.Parameters.Add(dbVersion);

                sqlConnection.Open();
                command.ExecuteNonQuery();
                sqlConnection.Close();
            }

            #endregion
        }

        /// <summary>
        /// Set this property to define a database connection string. This
        /// property can be used instead of the combination of <see cref="Microsoft.Sdc.Tasks.Sql.SetDatabaseVersion.ServerName"/> and
        /// <see cref="Microsoft.Sdc.Tasks.Sql.SetDatabaseVersion.DatabaseName"/>.
        /// </summary>
        public string ConnectionString
        {
            get
            {
                return (connectionString == null ? String.Empty : connectionString);
            }
            set
            {
                connectionString = value;

                return;
            }
        }

        /// <summary>
        /// The version number to set 
        /// </summary>
        public string DatabaseVersion
        {
            get { return databaseVersion; }
            set { databaseVersion = value; }
        }

        /// <summary>
        /// The SQL Server name.
        /// </summary>
        public string ServerName
        {
            get
            {
                return (serverName == null ? String.Empty : serverName);
            }
            set
            {
                serverName = value;

                return;
            }
        }

        /// <summary>
        /// Name of the database that the script will be run against.
        /// </summary>
        public string DatabaseName
        {
            get
            {
                return (databaseName == null ? String.Empty : databaseName);
            }
            set
            {
                databaseName = value;
                return;
            }
        }

        /// <summary>
        /// Gets or sets the wait time in seconds before terminating the 
        /// attempt to execute a command and generating an error.
        /// </summary>
        /// <remarks>
        /// Has a default value of 30 seconds.
        /// </remarks>
        public int CommandTimeout
        {
            get
            {
                return commandTimeout;
            }
            set
            {
                commandTimeout = value;
                return;
            }
        }
    }
}